// pages/vip/vipBuy.js
const app = getApp();
let tool = require('../../../utils/tool.js');
let md5 = require('../../../utils/md5.js');
const httpUtils = require('../../../utils/httpUtils.js');
let payStatusTimes = 0;

Page({

  /**
   * 页面的初始数据
   */
  data: {
    imageurl: 'https://yxpmaterial.oss-cn-beijing.aliyuncs.com/',
    total_fee: 198,
    title: '向易学派支付VIP会员费用',
    merchant: '易学派',
    order_no: '', //订单号
    content: '',
    vip:0, //是否是会员 vip 0非会员 ， vip 1 是会员
    vipType:'0', //开通会员类型，按年，半年，月
    amount:'198',
    pay_param: {
      // appid:'wxb2a30d4394478dfc',
      appid: 'wxebb42ec67a3e805b',
      // mch_id: '1519774121',    // 阳光易百
      // mch_key: "WhVNVFERtbe7vb6n7tvVRb7unt8BNTN9",
      mch_id: ' 1610258123',    
      mch_key: "A5E4A6AA47A020FF57295F359C094F07",
      type: 1,
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    let that = this;
    console.log("vipPay界面接收到的vipType="+options.vipType+",vip="+options.vip)
    that.setData({
      vipType:options.vipType,
      amount:options.amount,
      vip:options.vip,
    })
    that.getPayInfo();
  },

  /**
   * 获取支付详情信息
   */
  getPayInfo: function() {
    let that = this;
    wx.showLoading({
      title: '',
      mask: true
    })
    httpUtils.getPayinfo({
      access_token: app.globalData.studentInfo.access_token ? app.globalData.studentInfo.access_token : app.globalData.access_token,
    }).then((res) => {
      that.setData({
        total_fee: res.data.total_fee,
        title: res.data.title,
        merchant: res.data.payto,
      })
    })
  },

  /**
   * 开通会员
   */
  topay: function() {
    let that = this;
    let type =1;
    if(that.data.vip ==1){
      type =10;
    }else{
      type =1;
    }

    wx.showLoading({
      title: '',
      mask: true
    })
    httpUtils.tovip({
      access_token: app.globalData.studentInfo.access_token,
      org_id: app.globalData.studentInfo.org_id,
      type: type,
      vip_type:that.data.vipType,
      openid: app.globalData.studentInfo.openid,
    }).then((res) => {
      console.log(JSON.stringify(res))
      that.setData({
        order_no: res.data.order_no
      })
      //小程序调起支付API
      wx.requestPayment({
        timeStamp: res.data.timeStamp,
        nonceStr: res.data.nonceStr,
        package: res.data.package,
        signType: res.data.signType,
        paySign: res.data.paySign,
        success: function(res) {
          //成功后调查询支付结果接口
          that.checkPayStatus();
        },
        fail: function(res) {
          // fail  
          if (res.errMsg == "requestPayment:fail cancel") {
            wx.showToast({
              title: '取消支付',
              icon: 'none',
              duration: 2000
            })
          } else {
            wx.showToast({
              title: '支付失败',
              icon: 'none',
              duration: 2000
            })
          }
        }
      })
    })
  },

  /**
   * 获取支付结果状态
   */
  checkPayStatus: function() {
    let that = this;
    wx.showLoading({
      title: '获取支付结果...',
      mask: true
    })
    let paramArr = {
      access_token: app.globalData.studentInfo.access_token ? app.globalData.studentInfo.access_token : app.globalData.access_token,
      order_no: that.data.order_no
    }
    let rs = tool.getSign(paramArr, app.globalData.key); //返回 bodyParam heaer sign
    let sign = rs.sign;
    let apiUrl = app.globalData.apiURL + "user/checkstatus?sign=" + sign;
    let classPro = new Promise(
      function(resolve, reject) {
        wx.request({
          url: apiUrl,
          header: rs.header,
          data: rs.bodyParam,
          method: 'post',
          success(res) {
            resolve(res);
          }
        })
      }
    );

    classPro.then(function(res) {
      console.log(JSON.stringify(res))
      if (res.data.code === 1) {
        //支付成功
        wx.hideLoading();
        payStatusTimes = 0;
        wx.showToast({
          title: '支付成功',
          icon: 'success',
          duration: 2000
        })
        app.globalData.studentInfo.is_vip = 1;
        wx.switchTab({
          url: '../../../pages/mine/mine',
        })
      } else if (1082 == res.data.code) {
        //支付未完成，5s,15s,30s后再轮询查下结果
        if (payStatusTimes == 3) {
          payStatusTimes = 0;
          wx.showToast({
            title: res.data.info,
            icon: 'none',
            duration: 3000
          });
          return;
        }
        let waitTime = payStatusTimes == 0 ? 5000 : payStatusTimes == 1 ? 15000 : 30000;
        payStatusTimes++;
        setTimeout(function() {
          that.checkPayStatus()
        }, waitTime)

      } else {
        //失败或者其他
        wx.hideLoading();
        payStatusTimes = 0;
        wx.showToast({
          title: res.data.info,
          icon: 'none',
          duration: 3000
        });
      }

    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  },
  // getdata: function () {
  //   let that = this;
  //   let paramArr = {
  //     access_token: app.globalData.studentInfo.access_token,
  //     org_id:app.globalData.studentInfo.org_id,
  //     type: 1,
  //     openid: app.globalData.studentInfo.openid,

  //   }
  //   let rs = tool.getSign(paramArr, app.globalData.key); //返回 bodyParam heaer sign
  //   let sign = rs.sign;
  //   let apiUrl = app.globalData.apiURL + "user/tovip?sign=" + sign;
  //   let payPro = new Promise(
  //     function (resolve, reject) {
  //       wx.request({
  //         url: apiUrl,
  //         header: rs.header,
  //         data: rs.bodyParam,
  //         method: 'post',
  //         success(res) {
  //           resolve(res);
  //         }
  //       })
  //     }
  //   );
  //   return payPro;

  // },
  // topay: function () {
  //   let that = this;
  //   let payPro = that.getdata();
  //   payPro.then(function (res) {
  //     if (res.data.code == 1) {
  //       //封装统一支付xml参数
  //       //this.data.pay_param
  //       let nonce_str = tool.randomString();//随机字符串，不长于32位。
  //       let unifiedPayment = 'appid=' + that.data.pay_param.appid + '&body=' + res.data.data.body + '&mch_id=' + that.data.pay_param.mch_id + '&nonce_str=' + nonce_str + '&notify_url=' + res.data.data.notify_url + '&openid=' + app.globalData.studentInfo.openid + '&out_trade_no=' + res.data.data.order_no + '&spbill_create_ip=' + app.globalData.studentInfo.ip + '&total_fee=' + res.data.data.total_fee + '&trade_type=JSAPI&key=' + that.data.pay_param.mch_key;
  //       var sign = md5.md5(unifiedPayment).toUpperCase()
  //       let formData = "<xml>"
  //       formData += "<appid>" + that.data.pay_param.appid + "</appid>"
  //       formData += "<body>" + res.data.data.body + "</body>"
  //       formData += "<mch_id>" + that.data.pay_param.mch_id + "</mch_id>"
  //       formData += "<nonce_str>" + nonce_str + "</nonce_str>"
  //       formData += "<notify_url>" + res.data.data.notify_url + "</notify_url>"
  //       formData += "<openid>" + app.globalData.studentInfo.openid + "</openid>"
  //       formData += "<out_trade_no>" + res.data.data.order_no + "</out_trade_no>"
  //       formData += "<spbill_create_ip>" + app.globalData.studentInfo.ip + "</spbill_create_ip>"
  //       formData += "<total_fee>" + res.data.data.total_fee + "</total_fee>"
  //       formData += "<trade_type>JSAPI</trade_type>"
  //       formData += "<sign>" + sign + "</sign>"
  //       formData += "</xml>";
  //        that.payOperate(formData);
  //     } else if (res.data.code == 10001) {
  //         wx.redirectTo({
  //             url: '/pages/login/login',
  //         })
  //     }

  //   });
  // },
  // payOperate: function (formData) {
  //   let that = this;
  //   //统一支付
  //   wx.request({
  //     url: 'https://api.mch.weixin.qq.com/pay/unifiedorder',
  //     method: 'POST',
  //     head: 'application/x-www-form-urlencoded',
  //     data: formData, // 设置请求的 header
  //     success: function (res) {
  //       let result_code = that.getXMLNodeValue('result_code', res.data.toString("utf-8"))
  //       let resultCode = result_code.split('[')[2].split(']')[0]
  //       if (resultCode == 'FAIL') {
  //         var err_code_des = that.getXMLNodeValue('err_code_des', res.data.toString("utf-8"))
  //         var errDes = err_code_des.split('[')[2].split(']')[0]
  //         wx.navigateBack({
  //           delta: 1, // 回退前 delta(默认为1) 页面
  //           success: function (res) {
  //             wx.showToast({
  //               title: errDes,
  //               icon: 'success',
  //               duration: 2000
  //             })
  //           }
  //         })
  //       } else {
  //         //发起支付
  //         var prepay_id = that.getXMLNodeValue('prepay_id', res.data.toString("utf-8"))
  //         var tmp = prepay_id.split('[')
  //         var tmp1 = tmp[2].split(']')
  //         //签名
  //         var appId = that.data.pay_param.appid;
  //         var timeStamp = tool.createTimeStamp();
  //         var nonceStr = tool.randomString();
  //         var stringSignTemp = "appId=" + appId + "&nonceStr=" + nonceStr + "&package=prepay_id=" + tmp1[0] + "&signType=MD5&timeStamp=" + timeStamp + "&key=" + app.globalData.mch_key
  //         var sign = md5.md5(stringSignTemp).toUpperCase()
  //         var param = { "timeStamp": timeStamp, "package": 'prepay_id=' + tmp1[0], "paySign": sign, "signType": "MD5", "nonceStr": nonceStr }
  //         that.pay(param)
  //       }
  //     }
  //   })
  // },  /* 获取prepay_id */
  // getXMLNodeValue: function (node_name, xml) {
  //   var tmp = xml.split("<" + node_name + ">")
  //   var _tmp = tmp[1].split("</" + node_name + ">")
  //   return _tmp[0]
  // }, 
  // /**
  //  * 小程序调起支付API
  //  */
  // pay: function (param) {
  //   var that = this
  //   wx.requestPayment({
  //     timeStamp: param.timeStamp,
  //     nonceStr: param.nonceStr,
  //     package: param.package,
  //     signType: param.signType,
  //     paySign: param.paySign,
  //     success: function (res) {
  //       // success 
  //           wx.showToast({
  //             title: '支付成功',
  //             icon: 'success',
  //             duration: 2000
  //           })
  //       app.globalData.studentInfo.is_vip=1;
  //       wx.switchTab({
  //         url: '../../../pages/index/index',
  //       })

  //     },
  //     fail: function (res) {
  //       // fail  
  //       if (res.errMsg == "requestPayment:fail cancel"){
  //         wx.showToast({
  //           title: '取消支付',
  //           icon: 'none',
  //           duration: 2000
  //         })
  //       }else{
  //         wx.showToast({
  //           title: '支付失败',
  //           icon: 'none',
  //           duration: 2000
  //         })
  //       }

  //     }
  //   })
  // }
})